/**
 *
 */
package info.motteke.kurumi.swt;

import info.motteke.kurumi.SimpleStringVisitor;
import info.motteke.mixivoice4j.Voice;

import java.text.SimpleDateFormat;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;

final class VoiceAppender implements Runnable {
    private final List<Voice> list;

    private final SwtVoiceTable table;

    private final SwtImageCache imageCache;

    public VoiceAppender(SwtVoiceTable table, List<Voice> list, SwtImageCache imageCache) {
        this.list = list;
        this.table = table;
        this.imageCache = imageCache;
    }

    @Override
    public void run() {
        SwtVoiceTable.log.info("つぶやきの挿入を開始します。");
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        int index = 0;

        for (Voice voice : list) {
            index = search(voice);
            TableItem item = new TableItem(table.getTable(), SWT.NULL, index);

            String[] texts = {
                        voice.getUser().getNickName(),
                        voice.getBody(new SimpleStringVisitor()),
                        format.format(voice.getPostDate()),
                };

            item.setText(texts);
            item.setData(voice);
            item.setImage(0, imageCache.getImage(voice.getUser().getThumbnail().getUrl(), 16, 16));

            table.addItem(voice, item);
        }
    }

    private int search(Voice voice) {
        int index = 0;
        Table t = table.getTable();
        int length = t.getItemCount();

        for (index = 0; index < length; index++) {
            Voice v = (Voice) t.getItem(index).getData();
            if (v.getPostDate().before(voice.getPostDate())) {
                break;
            }
        }

        return index;
    }
}